<template>
  <div>
    <h4>商城首页</h4>
    <van-search
      v-model="keyWord"
      placeholder="请输入手机品牌"
      @search="onSearch"
    />
    <h4>推荐时间 {{ time }}</h4>
    <h4>当前时间 {{ new Date().toLocaleString() }}</h4>
    <h4>推荐品牌</h4>
    <div class="card-wrap">
      <div
        v-for="item in recommendList"
        :key="item.id"
        class="card"
        @click="search(item)"
      >
        {{ item.name }}
      </div>
    </div>

    <h4>热卖榜前十</h4>
    <div class="card-wrap">
      <div
        v-for="item in hotList"
        :key="item.id"
        class="card darkOrange"
        @click="gotoDetail(item)"
      >
        {{ item.name }}
      </div>
    </div>
  </div>
</template>

<script>
import { sleep } from '../utils';

const phoneBand = [
  {
    id: 1,
    name: '苹果',
  },
  {
    id: 2,
    name: '华为',
  },
  {
    id: 3,
    name: '小米',
  },
  {
    id: 4,
    name: 'OPPO',
  },
];

export default {
  name: 'shop',
  data() {
    return {
      keyWord: '',
      recommendList: [],
      hotList: [],
      time: new Date().toLocaleString(),
    }
  },
  activated() {
    if (this.$route.params.reload === '1') {
      console.log('shopinit')
      this.keyWord = ''
      this.recommendList = []
      this.hotList = []
      this.time = new Date().toLocaleString()
      this.getRecommendList()
      this.getHotList()
    }
  },
  methods: {
    getRecommendList() {
      sleep(100).then(() => {
        this.recommendList = phoneBand;
      });
    },
    getHotList() {
      sleep(100).then(() => {
        const phoneBandLength = phoneBand.length;
        for (let index = 0; index < 10; index++) {
          this.hotList.push({
            id: index,
            name:
              phoneBand[parseInt(Math.random() * phoneBandLength + '')].name +
              parseInt(Math.random() * 20 + ''),
          });
        }
      });
    },
    search(item) {
      this.keyWord = item.name;
      this.onSearch();
    },
    onSearch() {
      this.$router.push({
        name: 'list',
        params: {
          keyWord: this.keyWord,
        },
      });
    },
    gotoDetail(item) {
      this.$router.push({
        path: '/detail',
        query: {
          name: item.name,
        },
      });
    },
  }
}
</script>
<style lang="scss">
.card-wrap {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 20px;
  gap: 20px;
  color: #fff;
  .card {
    background-color: #000;
    text-align: center;
    width: calc((100% - 20px) / 2);
    line-height: 80px;
    &.darkOrange {
      background-color: DarkOrange;
    }
  }
}
</style>